package by.scsbsu.database.tools;

import java.sql.Connection;
import java.sql.DriverManager;
import org.apache.log4j.Logger;
import snaq.db.ConnectionPool;
import by.scsbsu.resources.managers.PoolManager;

import com.mysql.jdbc.Driver;

public class DbConnectionPool {

	private static final Logger LOGGER = Logger.getLogger("system_logger");
	
	private static final long TIMEOUT = 2000;
	private static ConnectionPool cp = null;
	private static Driver dbDriver = null;

	public static Connection getConnection() {
		synchronized (DbConnectionPool.class) {
			Connection connection = null;
			try {
				if (dbDriver == null) {
					registerDriver();
				}
				if (cp == null) {
					PoolManager pm = new PoolManager();
					cp = new ConnectionPool(pm.POOL_NAME, 
											pm.MIN_POOL, 
											pm.MAX_POOL, 
											pm.MAX_SIZE, 
											pm.IDLE_TIMEOUT, 
											pm.DB_URL, 
											pm.DB_USER, 
											pm.DB_PASSWORD);
				}
				connection = cp.getConnection(TIMEOUT);
				LOGGER.info("Connection was successfully obtained from Connection Pool!");
			} 
			catch(Exception e) {
				LOGGER.error("Problem with Connection Pool!");
			}
			return connection;
		}
	}

	private static void registerDriver() throws Exception {
		dbDriver = (Driver)Class.forName(new PoolManager().DB_DRIVER).newInstance();
		DriverManager.registerDriver(dbDriver);
	}
}
